package com.pituruh.tjroute;

import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.pituruh.utils.RouteSitesList;
import com.pituruh.utils.RouteXMLHandler;
import com.pituruh.utils.ShelterSitesList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TableRow.LayoutParams;

public class Route extends Activity implements Runnable {
	//ProgressDialog pd;
	ArrayList<String> listItems = null;
	RouteSitesList sitesList;
	Integer selectedRoute;
	ProgressBar pb;
	
	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route);
        
        Resources res = getResources();
        int colors[] =  {res.getColor(R.color.actionbar_color_1),res.getColor(R.color.actionbar_color_2)};
        GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
        LinearLayout layout = (LinearLayout) findViewById(R.id.buttonlayout);
        layout.setBackgroundDrawable(grad);
        
        TextView title_bar = (TextView) findViewById(R.id.title_bar);
        title_bar.setText(R.string.trayek);
        
        ImageButton btnShare = (ImageButton) findViewById(R.id.btn_share);
        btnShare.setVisibility(View.VISIBLE);
        ImageView imgSeparator = (ImageView) findViewById(R.id.title_separator);
        imgSeparator.setVisibility(View.VISIBLE);
        
		/****progress dialog***/
/*		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_data_from_server), true,
				false);
*/		pb = (ProgressBar) findViewById(R.id.title_progress);
		pb.setVisibility(View.VISIBLE);
        Thread thread = new Thread(this);
		thread.start();

		/****end of progress dialog***/
    
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 0, 0, "Peta");
/*		menu.add(0, 1, 0,"Cari Lokasi");
		menu.add(0, 2, 0,"CheckBox");
		menu.add(0, 3, 0,"EditText");
		menu.add(0, 4, 0,"RadioGroup");
		menu.add(0, 5, 0,"Settings");
*/		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return(applyMenuChoice(item) ||
				super.onOptionsItemSelected(item));
	}

	private boolean applyMenuChoice(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Intent newIntent = new Intent(this.getApplicationContext(),
					RouteMap.class);
			newIntent.putExtra("selectedRoute",selectedRoute);
	    	startActivity(newIntent);
			return true;
		}
		return false;
	}
    
	public void run() {
		try {
			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
			"http://transjogja.only.web.id/app/xml/route.xml");


			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			RouteXMLHandler myXMLHandler = new RouteXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

			/** Get result from MyXMLHandler SitlesList Object */
			sitesList = RouteXMLHandler.routeList;

			listItems = new ArrayList<String>();
			for (int i = 0; i < sitesList.getName().size(); i++) {
				listItems.add(sitesList.getName().get(i));
			}

		} catch (Exception e) {
			System.out.println("XML Parsing Exception = " + e);
		}
		handler.sendEmptyMessage(0);
		
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			//pd.dismiss();
			pb.setVisibility(View.GONE);
			
			if (listItems == null) {
				Toast.makeText(getApplicationContext(), R.string.failed_loading, Toast.LENGTH_SHORT)
							.show();
				finish();
			}
			else {
				setupSpinner();
			}
		}
	};
	
	private void setupSpinner(){
		Spinner spinner = (Spinner) findViewById(R.id.shelter_list);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, listItems);

		adapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
		        // your code here
		    	populateRoute(position);
		    	selectedRoute = position;
		    }

		    @Override
		    public void onNothingSelected(AdapterView<?> parentView) {
		        // your code here
		    }

		});
	}
	
	private void populateRoute(Integer index) {
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayoutList);
        tl.removeAllViews();

        Integer current = 0;
        ShelterSitesList shelterSites = sitesList.getShelters().get(index);
        
        for (int i = 0; i < shelterSites.getName().size(); i++) {
	           // Create a TableRow and give it an ID
            TableRow tr = new TableRow(this);
            tr.setId(100+current);
            LayoutParams tr_lp = new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            tr_lp.setMargins(10,0,0,0);
            tr.setLayoutParams(tr_lp);   

            // Create a TextView to house the name of the province
            TextView labelName = new TextView(this);
            labelName.setId(200+current);
            labelName.setText(shelterSites.getName().get(i));
            labelName.setTextColor(Color.BLACK);
            labelName.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));
            tr.addView(labelName);

            String distance = shelterSites.getDistance().get(i) + " km";
            TextView labelKM = new TextView(this);
            labelKM.setId(current);
            labelKM.setText(distance);
            labelKM.setGravity(Gravity.RIGHT);
            labelKM.setTextColor(Color.BLACK);
            LayoutParams labelKM_layout = new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            labelKM.setLayoutParams(labelKM_layout);
            tr.addView(labelKM);
            // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));		
            
            current++;
		}
	}
    
    public void onHomeClick(View v) {
    	startActivity(new Intent(Route.this, TJRoute.class));
    }
    
    public void onCariClick(View v) {
    	startActivity(new Intent(Route.this, FindRoute.class));
    }
    
    public void onShareClick(View v) {
        final String shareText = getString(R.string.share);

        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("plain/html");
        intent.putExtra(Intent.EXTRA_SUBJECT, shareText);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        intent.putExtra(Intent.EXTRA_STREAM, "tstestat aastst");

        startActivity(Intent.createChooser(intent, getText(R.string.share)));
    }

/*    public void onMapClick(View v) {
		Intent newIntent = new Intent(this.getApplicationContext(),
				RouteMap.class);
//		int activityID = 0x101;
		newIntent.putExtra("selectedRoute",selectedRoute);
//		startActivityForResult(newIntent, activityID);
    	startActivity(newIntent);
    }*/
}
